<template>
  <su-page>
    <su-body padding="0 15px">
      <u--form labelPosition="top" :model="formData" :rules="rules" ref="fqlcform">
        <u-form-item labelWidth="100px" label="流程标题" prop="lcbt" borderBottom required>
          <u--input v-model="formData.lcbt" placeholder="请输入流程标题" border="none"></u--input>
        </u-form-item>
        <!-- <u-form-item labelWidth="100px" label="接收单位" prop="jsdw" @click="clickJsdw()" borderBottom required>
		  <u--input
		  		v-model="formData.jsdw"
		  		border="none"
		  		disabled
		  		placeholder="请选择接收单位"
		  ></u--input>
		  <u-icon
		  	slot="right"
		  	name="arrow-right"
		  ></u-icon>
        </u-form-item> -->
		<u-form-item 
			labelWidth="100px" 
			label="接收单位" 
			prop="jsdw" @click="clickJsdw()" borderBottom required class="ndistinct">
		  <u--textarea
		  		v-model="formData.jsdw"
		  		border="none"
		  		disabled
				autoHeight 
		  		placeholder="请选择接收单位"
		  ></u--textarea>
		  <u-icon
		  	slot="right"
		  	name="arrow-right"
		  ></u-icon>
		</u-form-item>
		<view class="ndistinct-list" v-if="showJsdw">
			 <u-checkbox-group
			            v-model="jsdwList"
			            placement="column"
						@change="checkJsdw"
						ref="jsdwcheck"
			        >
				<u-checkbox
					:customStyle="{marginBottom: '8px'}"
					v-for="(item, index) in jsdwLists"
					:key="index"
					:label="item.name"
					:name="item.name"
				>
				</u-checkbox>
			</u-checkbox-group>
		</view>
		<u-form-item labelWidth="100px" label="接收人" prop="jsr" @click="clickJsr()" borderBottom required class="ndistinct">
<!-- 		  <u--input
		  		v-model="formData.jsr"
		  		border="none"
		  		disabled
		  		placeholder="请选择接收人"
		  ></u--input> -->
		  <u--textarea
		  		v-model="formData.jsr"
		  		border="none"
		  		disabled
		  		autoHeight 
		  		placeholder="请选择接收人"
		  ></u--textarea>
		  <u-icon
		  	slot="right"
		  	name="arrow-right"
		  ></u-icon>
		</u-form-item>
		<view class="ndistinct-list" v-if="showJsr">
			 <u-checkbox-group
			            v-model="JsrList"
			            placement="column"
						@change="checkJsr"
						ref="jsrcheck"
			        >
				<u-checkbox
					:customStyle="{marginBottom: '8px'}"
					v-for="(item, index) in JsrLists"
					:key="index"
					:label="item.name"
					:name="item.name"
				>
				</u-checkbox>
			</u-checkbox-group>
		</view>
        <u-form-item labelWidth="100px" label="意见建议" prop="yjjy" borderBottom required>
          <u--textarea v-model="formData.yjjy" placeholder="请输入意见建议"  border="none"></u--textarea>
        </u-form-item>
<!-- 		<u-form-item
				label="附件"
				prop="fj"
				required
		>
			<u-upload
				:fileList="formData.fj"
				@afterRead="afterRead"
				@delete="deletePic"
				name="3"
				multiple
				:maxCount="10"
				:previewFullImage="true"
			></u-upload>
		</u-form-item> -->
		<u-form-item labelWidth="100px" label="附件" prop="fjid" borderBottom>
			<view class="su-uploader">
				<view class="su-uploader-handler" @click="chooseWxFile">
				  +
				</view>
				<view class="su-uploader-images-item" v-for="(item,index) in formData.fjid" :key="index">
				  <view class="su-uploader-images-delete" @click="deleteItem(item,index)">
					<u-icon name="close" color="#ff0000" size="18"></u-icon>
				  </view>
				  <u--image radius="6" :src="item.imgurl" width="70" height="70" mode="aspectFill" @click="previewImg(index)"></u--image>
				</view>
			</view>
		</u-form-item>
      </u--form>
      <su-fixed-footer transparent>
        <u-button type="primary" size="large" :loading="loading" text="发送" @click="submitForm"></u-button>
      </su-fixed-footer>
	  <!-- <u-action-sheet
	  	:show="showJsdw"
	  	:actions="jsdwList"
	  	title="请选择接收单位"
	  	@close="closeJsdw"
	  	@select="jsdwSelect"
	  >
	  </u-action-sheet> -->
<!-- 	  <u-action-sheet
	  	:show="showJsr"
	  	:actions="JsrList"
	  	title="请选择接收人"
	  	@close="showJsr = false"
	  	@select="jsrSelect"
	  >
	  </u-action-sheet> -->
    </su-body>
		<u-toast ref="uToast"></u-toast>
  </su-page>
</template>

<script>
  /**
    * @Description:发起流程
    * @author:神仙姐姐
    * @param 
    * @return 
    * @createTime: 2022-11-22 14:51:05
    * @Copyright by 神仙姐姐
    */
   let fileIcon = ``
  import {
    register
  } from '@/common/api.js'
  import {runSQL, uploadFilePath} from '@/common/utils/wxutils.js'
  export default {
    data() {
      return {
		jsArr:[],
		showJsdw:false,
		showJsr:false,
        loading: false,
		jsdwLists: [],//罗列全部
		jsdwList:[],
		jsdwidList:[],
		JsrLists:[],//罗列全部
		JsrList:[],
		JsridList:[],
		fileStr:'',
        // form表单数据对象	
        formData: {
          lcbt: '',
          jsdw: '',
		  jsdwid:'',
		  // jsdwid:0,
		  jsr: '',
		  jsrid:'',
		  // jsrid:0,
		  fsr:JSON.parse(uni.getStorageSync('userInfo')).HUMANNAME,
		  fsrid:JSON.parse(uni.getStorageSync('userInfo')).HUMANID,
		  fsdwid:JSON.parse(uni.getStorageSync('userInfo')).UNITID,
		  fsdw:JSON.parse(uni.getStorageSync('userInfo')).UNITNAME,
          yjjy: '',
          fj:[],
		  fjid:[],
        },
        // 表单校验规则
        rules: {
          lcbt: [{
            required: true,
            message: '请填写流程标题',
            trigger: ['change', 'blur'],
          }],
          yjjy: [{
            required: true,
            message: '请填写意见建议',
            trigger: ['change', 'blur'],
          }],
          jsdw: {
            required: true,
            validator: (rule, value, callback) => {
              return value !== '';
            },
            message: '请选择接收单位',
            trigger: ['change'],
          },
		  jsr: {
		    required: true,
		    validator: (rule, value, callback) => {
		      return value !== '';
		    },
		    message: '请选择接收人',
		    trigger: ['change'],
		  },
        }
      }
    },
    onLoad() {
      this.$nextTick(()=>{
        this.$refs.fqlcform.setRules(this.rules)
      })
    },
	mounted() {
		this.initjsdw();
	},
    methods: {
	  jsdwSelect(e){
			this.formData.jsdw = e.name;
			this.formData.jsdwid = e.id;
			this.initjsr(e.id)
		},
		checkJsdw(name){
			let arr = this.$refs.jsdwcheck.children
			let dwlist = [];
			for(let a=0;a<arr.length;a++){
				if(arr[a].isChecked){
					dwlist.push(this.jsdwLists.find(item=>{
						if(item.name == arr[a].name){
							return item
						}
					}).id)
				}
			}
			let changedw = name.toString();
			this.formData.jsdw = changedw
			this.formData.jsdwid = dwlist.join(',')
			this.jsdwidList = dwlist
		},
		checkJsr(name){
			let arrs = this.$refs.jsrcheck.children
			let rylist = [];
			for(let a=0;a<arrs.length;a++){
				if(arrs[a].isChecked){
					rylist.push(this.JsrLists.find(item=>{
						if(item.name == arrs[a].name){
							return item
						}
					}).id)
				}
			}
			let changery = name.toString();
			this.formData.jsr = changery
			this.formData.jsrid = rylist.join(',')
			this.JsridList = rylist
		},
		closeJsdw(){
			this.showJsdw = false;
		},
		jsrSelect(e){
			this.formData.jsr = e.name;
			this.formData.jsrid = e.id;
		},
		clickJsdw(){
			this.showJsdw = !this.showJsdw;
			if(this.showJsr){
				this.showJsr = !this.showJsr;
			}
		},
		changejsdwbox(id){
			console.log(id)
		},
		clickJsr(){
			if(this.formData.jsdw == '' || this.formData.jsdw == null){
				uni.$u.toast('请先选择接收单位');
				return
			}
			this.showJsr = !this.showJsr;
			this.initjsr()
		},
		chooseWxFile(){
			let sthis = this;
			// #ifdef MP-WEIXIN
			wx.chooseMessageFile({
				count: 9,
				type: 'all',
				success: (res)=>{
					const tempFilePaths = res.tempFiles;
					tempFilePaths.forEach(file => {
						if(!(/png|jpg|jpeg/.test(file.path.toLocaleLowerCase()))){
							file.imgurl = fileIcon
						}else{
							file.imgurl = file.path
						}
					})
					
					sthis.formData.fjid = sthis.formData.fjid.concat(tempFilePaths)
				}
			})
			// #endif

		},
		uploadFileAsync(recid, url) {
			let _this = this;
			return new Promise( async (resolve, reject)=>{
				await uni.uploadFile({
					url: uploadFilePath,
					filePath: url,
					name: 'file',
					formData: {
						recid: recid
					},
					success: (res) => {
						let data = JSON.parse(res.data);
						let reg =  new RegExp("\\/"+data.wjm);
						let url_n = data.url.replace(/D:\/\/SSNYDWFile/,'').replace(reg, '');
						data.url = url_n;
						resolve(data)
					}
				});
			})
		},
		deleteItem(item,index){
			this.formData.fjid.splice(index, 1)
		},
		previewImg(index){
			let sthis = this;
			let arr = [];
			if(sthis.formData.fjid.length>0){
				for(let a=0;a<sthis.formData.fjid.length;a++){
					arr.push(sthis.formData.fjid[a].path)
				}
			}
			// return
			wx.previewImage({
			   urls: arr,
			   current: index
			})
			
			// wx.downloadFile({
			//   //文件url
			//   url: sthis.formData.fjid[index].path,
			//   success: function (res) {
			//     const filePath = res.tempFilePath
			//     wx.openDocument({
			//       filePath: filePath,
			//       success: function (res) {
			//         console.log('打开文档成功')
			//       },
			//       fail: function (res) {
			//         console.log('打开文档失败')
			//       },
			//     })
			//   }
			// })
		},
	  initjsdw(){
		  //主管部门
		  runSQL(`select UNITNAME,UNITID from ssnydw.tbunit where parentid = 2358;`).then(res=>{
			  if(res[0].length>0){
				  for(let a=0;a<res[0].length;a++){
					  this.jsdwLists.push({
					  	name : res[0][a].UNITNAME,
					  	id : res[0][a].UNITID,
						disabled: false
					  })
				  }
			  }
		  })
	  },
	  initjsr(){
		  this.JsrLists.length = 0;
		  console.log(this.jsdwidList)
		  for(let b=0;b<this.jsdwidList.length;b++){
			  runSQL(`select HUMANNAME,HUMANID from ssnydw.tbhuman where unitid = '${this.jsdwidList[b]}' or unitid in (select cast(unitid as varchar) from ssnydw.tbunit where parentid = ${this.jsdwidList[b]});`).then(ress=>{
				  if(ress[0].length>0){
					  for(let a=0;a<ress[0].length;a++){
						  this.JsrLists.push({
							name : ress[0][a].HUMANNAME,
							id : ress[0][a].HUMANID,
							disabled: false
						  })
					  }
				  }
			  })
		  }
		  console.log(this.JsrLists)
		  console.log(this.jsArr)
	  },
	  deletePic(event) {
	  	this.formData.fj.splice(event.index, 1)
	  	this.formData.fjid.splice(event.index, 1)
	  },
	  async afterRead(event) {
	  	let lists = [].concat(event.file)
	  	let fileListLen = this.formData.fj.length
	  	lists.map((item) => {
	  		this.formData.fj.push({
	  			...item,
	  			status: 'uploading',
	  			message: '上传中'
	  		})
	  	})
	  	for (let i = 0; i < lists.length; i++) {
	  		const result = await this.uploadFilePromise(lists[i].url);
	  		// this.insertImg(result);
	  		let item = this.formData.fj[fileListLen]
	  		this.formData.fj.splice(fileListLen, 1, Object.assign(item, {
	  			status: 'success',
	  			message: '',
	  			data:JSON.parse(result.data)
	  			// url: result
	  		}))
	  		fileListLen++
	  	}
	  },
	  uploadFilePromise(url) {
	  	let vthis = this;
	  	return new Promise((resolve, reject) => {
	  		let a = uni.uploadFile({
	  			url: 'http://120.221.95.208:8083/HdzjAppport/uploadb', // 仅为示例，非真实的接口地址`${zhhfurl}zhhf-info/WeChat/getOpenId`,
	  			filePath: url,
	  			name: 'file',
	  			formData: {
	  				user: 'test'
	  			},
	  			success: (res) => {
	  				let obj = JSON.parse(res.data)
					let oo = JSON.stringify(obj)
	  				setTimeout(() => {
	  					vthis.formData.fjid.push(
	  						obj.fjid
	  					)
	  					resolve(res);
	  				}, 1000)
	  			},
				fail(err) {
					console.log(err)
				}
	  		});
	  	})
	  },
      // 提交表单
      submitForm() {
		  let sthis = this;
        this.$refs.fqlcform.validate().then(ok => {
          if (ok) {
			runSQL(`select o_recid from ssnydw.fnstartworkflowsql(243721,${sthis.formData.fsrid});`).then(res=>{
				if(res[0].length>0){
					runSQL(`insert into FQLC(recid,LCBT,JSDW,YJJY,FSDW,FSR,FSRID,FQSJ,JSR,JSRID,FSDWID,JSDWID)values(${res[0][0].O_RECID},'${sthis.formData.lcbt}','${sthis.formData.jsdw}',
					'${sthis.formData.yjjy}','${sthis.formData.fsdw}','${sthis.formData.fsr}',${sthis.formData.fsrid},
					now(),'${sthis.formData.jsr}','${sthis.formData.jsrid}',${sthis.formData.fsdwid},'${sthis.formData.jsdwid}');`).then(async oo=>{
						if(oo[0]==1){
							if(sthis.formData.fjid){
								let recid = res[0][0].O_RECID;
								// sthis.formData.fjid.forEach(file => {
								for(let i=0;i<sthis.formData.fjid.length;i++){
									let file = sthis.formData.fjid[i]
									await sthis.uploadFileAsync(recid, file.path).then(f=>{
										sthis.fileStr = sthis.fileStr + f.fileid + ","
										runSQL(`insert into ssnydw.tbfile(fileid,filename,filepath,filesize,lastupdate,humanid,
										storefilename,serverid,folderid,disporder,version) 
										values('${f.fileid}','${f.wjm}','${f.url}',100,now(),${sthis.formData.fsrid},
										'${f.wjm}',1,${recid},1,1);`).then(i => {
											console.log(i);
										});
									})
								}
								runSQL(`update FQLC set fjid = '${sthis.fileStr.substring(0,sthis.fileStr.length-1)}' where recid = ${recid};`).then(u => {
									this.$refs.uToast.show({
										type: 'success',
										message: "已发送",
										complete(){
											uni.navigateBack({
												delta: 1
											})
										}
									})
								})
							}else{
								this.$refs.uToast.show({
									type: 'success',
									message: "已发送",
									complete(){
										uni.navigateBack({
											delta: 1
										})
									}
								})
							}
							//插入附件表
							// if(sthis.formData.fj.length>0){
							// 	//说明有附件
							// 	for(let a=0;a<sthis.formData.fj.length;a++){
							// 		console.log(sthis.formData.fj)
							// 		return
							// 		runSQL(`INSERT INTO ssnydw.tbfile(fileid, filename, filepath, lastupdate, humanid, 
							// 		storefilename, serverid, folderid, version)
							// 		VALUES ('${sthis.formData.fj[a].data.fileid}','${sthis.formData.fj[a].data.filename}',
							// 		'${sthis.formData.fj[a].data.filepath}',now(),${sthis.formData.fsrid},'${sthis.formData.fj[a].data.storefilename}',
							// 		 1,${bb[0][0].O_RECID},1);`).then(ss=>{
							// 			 if(ss[0]==1){
							// 				 uni.$u.toast('发送成功');
							// 				 setTimeout(()=>{
							// 				 	uni.reLaunch({
							// 				 		url:'../../home/home'
							// 				 	})
							// 				 },1000)
							// 			 }else{
							// 				 console.log("上传附件失败")
							// 			 }
							// 		 })
							// 	}
							// }else{
							// 	uni.$u.toast('发送成功');
							// 	setTimeout(()=>{
							// 		uni.reLaunch({
							// 			url:'../../home/home'
							// 		})
							// 	},1000)
							// }
						}else{
							sthis.$refs.uToast.show({
								type: 'error',
								message: "发送失败，请重试"
							})
						}
					})
				}
			})
            // this.loading = true
            // setTimeout(() => {
            //   this.loading = false
            //   this.$u.toast('保存成功')
            //   this.$u.route({
            //     type: 'back'
            //   })
            // }, 500)
          }
        }).catch(err => {
          return
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/ .u-transition{
	min-height: 180px;
	max-height: 420px;
	overflow-y: auto;
}
	.ndistinct{
		position: relative;
	}
	.ndistinct-list{
		z-index: 3;
		position: absolute;
		background-color: #fff;
		border-right: 1px solid #ddd;
		border-bottom: 1px solid #ddd;
		border-left: 1px solid #ddd;
		height: 125px;
		line-height: 24px;
		padding: 3px 0 1px 12px;
		width: 86%;
		overflow-y: auto;
	}
	.ndistinct-lists{
		display: flex;
		margin-bottom: 10px;
	}
	.ndistinct-list-name{
		color: #333333;
		font-size: 16px;
	}
	.su-uploader{
	  display: flex;
	  flex-wrap: wrap;
	  &-handler{
	    width: 140upx;
	    height: 140upx;
	    border-radius: 6px;
	    background-color: #f7f7f7;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    font-size: 32px;
	    color: #999;
	    margin-right: 20upx;
	    line-height: 1;
	    &:active{
	      opacity: 0.6;
	    }
	  }
	  
	  &-images{
	    width: 140upx;
	    height: 140upx;
	    border-radius: 6px;
	    position: relative;
	    &-delete{
	      position: absolute;
	      width: 54upx;
	      height: 54upx;
	      background-color: rgba(0,0,0,0.6);
	      display: flex;
	      justify-content: center;
	      align-items: center;
	      color: #fff;
	      z-index: 3;
	      top: 0;
	      right: 0;
	      border-radius: 0 6px 0 6px;
	      &:active{
	        opacity: 0.7;
	      }
	    }
	    &-item{
	      display: flex;
	      position: relative;
	      margin-right: 20upx;
	    }
	  }
	}
</style>
